package com.pacy.pacybaseproject.net;


import com.pacy.pacybaseproject.base.BaseResultBean;
import com.pacy.pacybaseproject.utils.XUtils;

import java.io.IOException;
import java.nio.charset.Charset;

import me.goldze.mvvmhabit.utils.JsonUtil;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * @author PACY
 * @date 2022/1/20
 * description:
 */
public class TokenInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {

        Request originalRequest = chain.request();
        Response response = chain.proceed(originalRequest);
        ResponseBody responseBody = response.body();
        //解决response.body().string();只能打印一次
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();
        Charset UTF8 = Charset.forName("UTF-8");
        String string = buffer.clone().readString(UTF8);

        BaseResultBean baseResponseBean = JsonUtil.jsonToObject(string, BaseResultBean.class);
        if (baseResponseBean.getCode() == 401||baseResponseBean.getCode() == 403) {
            //refreshToken过期
//            ToastUtils.show("登录已过期，请重新登录");
//            XUtils.toLoginPage();
        }
        return response;
    }

}
